package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
)

func walkDir(dir string, filesize chan<- int64) {
	for _, entry := range dirents(dir) {
		if entry.IsDir() {
			subDir := filepath.Join(dir, entry.Name())
			walkDir(subDir, filesize)
		} else {
			fileinfo, _ := entry.Info()
			filesize <- fileinfo.Size()
		}

	}
}

func dirents(dir string) []os.DirEntry {
	entries, err := os.ReadDir(dir)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
	//
	return entries
}

func main() {
	flag.Parse()
	roots := flag.Args()
	if len(roots) == 0 {
		fmt.Fprintln(os.Stderr, len(roots))
		return
	}

	//
	filesizes := make(chan int64)
	go func() {
		for _, root := range roots {
			walkDir(root, filesizes)
		}
		close(filesizes)
	}()

	var nbytes, nfiles int64

	for filesize := range filesizes {
		nbytes += filesize
		nfiles += 1
	}

	printDiskUsage(nfiles, nbytes)
}

func printDiskUsage(nfiles, nbytes int64) {
	fmt.Printf("%d files   %1.f GB\n", nfiles, float64(nbytes)/1e9)
}
